package com.itheima.controller;

import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.itheima.mapper.DeptMapper;
import com.itheima.pojo.*;
import com.itheima.service.DeptService;
import com.itheima.service.EmpExprService;
import com.itheima.service.EmpService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Slf4j
@RestController
@RequestMapping("/emps")
public class EmpController {
    @Autowired
    private EmpService empService;
    @Autowired
    private DeptService deptService;
    @Autowired
    private EmpExprService empExprService;

    @GetMapping
    public Result page(EmpQueryParam param) {
        log.info("员工列表查询条件：{}", param);
        Page<Emp> page = Page.of(param.getPage(), param.getPageSize());
        page.addOrder(OrderItem.desc("update_time"));
        empService.page(page, Wrappers.<Emp>lambdaQuery()
                .like(StrUtil.isNotBlank(param.getName()), Emp::getName, param.getName())
                .eq(param.getGender()!=null, Emp::getGender, param.getGender())
                .between(param.getBegin()!=null && param.getEnd() !=null,Emp::getEntryDate,param.getBegin(),param.getEnd())
        );
        Integer total = (int) page.getTotal();
        List<Emp> list = page.getRecords();
        PageResult<Emp> pageResult = new PageResult<>(total, list);
        //获取所有员工的id
        Set<Long> empIds = list.stream().map(emp -> emp.getDeptId()).collect(Collectors.toSet());
        //查询员工对应的部门信息
        List<Dept> depts = deptService.listByIds(empIds);
        //将部门名称封装到员工的对象中
        list.forEach(emp -> {
            depts.stream().filter(dept -> dept.getId().equals(emp.getDeptId()))
                    .findFirst().ifPresent(dept -> emp.setDeptName(dept.getName()));
        });
        return Result.success(pageResult);
    }

    @PostMapping
    @Transactional(rollbackFor = Exception.class)
    public Result save(@RequestBody Emp emp) {
        log.info("新增员工，员工信息：{}", emp);
        empService.save(emp);
        //添加员工的工作经历
        List<EmpExpr> empExprList=emp.getExprList();
        empExprList.forEach(expr -> {
            expr.setEmpId(Long.valueOf(emp.getId()));
        });
        // 新增工作经历信息
        empExprService.saveBatch(empExprList);
        return Result.success();
    }

    @DeleteMapping
    public Result delete(@RequestParam List<Long> ids) {
        log.info("批量删除学生，{}", ids);
        empService.removeByIds(ids);
        boolean flag = empService.count(Wrappers.<Emp>lambdaQuery().in(Emp::getId, ids))>0;
        if (flag==false){
            return Result.success();
        }
        //删除员工的工作经历
        empExprService.remove(Wrappers.<EmpExpr>lambdaQuery().in(EmpExpr::getEmpId, ids));
        return Result.success();

    }

    @GetMapping("/{id}")
    public Result getById(@PathVariable Long id) {
        log.info("根据ID查询员工信息，id：{}", id);
        Emp emp = empService.getById(id);
        // 查询员工的部门名称
        Dept dept = deptService.lambdaQuery().eq(Dept::getId, emp.getDeptId()).one();
        emp.setDeptName(dept.getName());
        List<EmpExpr> exprList = empExprService.lambdaQuery().eq(EmpExpr::getEmpId, id).list();
        emp.setExprList(exprList);
        return Result.success(emp);
    }

    @PutMapping
    public Result update(@RequestBody Emp emp) {
        log.info("修改员工信息，员工信息：{}", emp);
        emp.setUpdateTime(LocalDateTime.now());
        empService.updateById(emp);
        //删除之前的信息
        empExprService.remove(Wrappers.<EmpExpr>lambdaQuery().eq(EmpExpr::getEmpId, emp.getId()));
        //保留现在的信息
        List<EmpExpr> exprList = emp.getExprList();
        exprList.forEach(expr -> {
            expr.setEmpId(Long.valueOf(emp.getId()));
        });
        empExprService.saveBatch(exprList);
        return Result.success();
    }

    @GetMapping("/list")
    public Result list() {
        log.info("查询员工列表");

        // 调用service层方法查询员工列表
        return Result.success();
    }
}
